/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.transaction.dubbo.proxy;

import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.proxy.InvokerInvocationHandler;
import com.alibaba.fastjson.JSON;
import com.lvyh.lightframe.transaction.annotation.MyTransaction;
import com.lvyh.lightframe.transaction.common.constant.TransactionConstant;
import com.lvyh.lightframe.transaction.common.context.TransactionContext;
import com.lvyh.lightframe.transaction.common.domain.Participant;
import com.lvyh.lightframe.transaction.common.domain.RPCErrorInfo;
import com.lvyh.lightframe.transaction.common.thread.TransactionThreadLocal;
import com.lvyh.lightframe.transaction.core.context.ApplicationContextHolder;
import com.lvyh.lightframe.transaction.core.coordinator.TransactionCoordinatorSupport;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * Wrap Dubbo's InvokerInvocationHandler's invoke method
 * For remote methods with distributed transactions enabled, do the following:
 * 1. The exceptions thrown by Dubbo are handled by itself and not thrown out, so as to ensure the normal execution of the transaction method without interruption. Finally, a reliable MQ message is sent (the exception information can be recorded)
 * 2. If the transaction context object exists locally, it is stored in the RPC interface parameters and passed to the remote method
 * 33. Add a transaction participant for the current transaction, and the participant is the called remote method
 */
@Slf4j
public class CustomInvokerInvocationHandler extends InvokerInvocationHandler {

    private Object target;


    public CustomInvokerInvocationHandler(final Invoker<?> handler) {
        super(handler);
    }

    public <T> CustomInvokerInvocationHandler(final T target, final Invoker<T> handler) {
        super(handler);
        this.target = target;
    }

    @Override
    public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
        MyTransaction myTransaction = method.getAnnotation(MyTransaction.class);
        if (Objects.nonNull(myTransaction)) {
            try {
                /**
                 * Only the initiator will enter this method and pass the context parameters to the downstream participant service
                 * the transaction initiator passes the transaction context info to the downstream participant service
                 */
                log.info("1. Enter Dubbo custom handler and call the following method:", method.getName());

                //Get the current transaction context object through ThreadLocal
                TransactionContext transactionContext = TransactionThreadLocal.CONTEXT_THREADLOCAL.get();

                //If the current transaction context object is not null, do the following
                if (Objects.nonNull(transactionContext)) {

                    //The transaction context object is passed to the remote method as an RPC interface parameter
                    RpcContext.getContext().setAttachment(TransactionConstant.TRANSACTION_CONTEXT, JSON.toJSONString(transactionContext));
                    log.info("2. Pass the transaction participant context object as an RPC interface parameter to the remote method:" + JSON.toJSONString(transactionContext));

                    //Add a transaction participant for the current transaction, and the participant is the called remote method
                    Participant participant = new Participant();
                    participant.setTransactionId(transactionContext.getTransactionId());
                    participant.setMessageModel(myTransaction.deliveryModel().getCode());
                    participant.setDestination(myTransaction.destination());
                    participant.setTargetClass(method.getDeclaringClass());
                    participant.setMethodName(method.getName());
                    participant.setParameterTypes(method.getParameterTypes());
                    participant.setArguments(args);

                    TransactionCoordinatorSupport transactionCoordinatorSupport = ApplicationContextHolder.getBean(TransactionCoordinatorSupport.class);
                    transactionCoordinatorSupport.addParticipant(participant);
                    log.info("3. Add transaction participant:" + participant.getTargetClass() + "." + participant.getMethodName());
                }
                return super.invoke(target, method, args);
            } catch (Throwable t) {
                log.error(t.getMessage());
                //Record the error message
                RPCErrorInfo rpcErrorInfo = new RPCErrorInfo();
                rpcErrorInfo.setCode(1);
                rpcErrorInfo.setErrorMsg(t.getMessage());
                TransactionThreadLocal.RPC_ERROR_INFO_THREADLOCAL.set(rpcErrorInfo);
                return handleRtnValue(method.getReturnType());
            }
        } else {
            return super.invoke(target, method, args);
        }
    }

    public Object handleRtnValue(final Class clazz) throws Exception {
        if (boolean.class.equals(clazz) || Boolean.class.equals(clazz)) {
            return false;
        } else if (byte.class.equals(clazz) || Byte.class.equals(clazz)) {
            return 0;
        } else if (short.class.equals(clazz) || Short.class.equals(clazz)) {
            return 0;
        } else if (int.class.equals(clazz) || Integer.class.equals(clazz)) {
            return 0;
        } else if (long.class.equals(clazz) || Long.class.equals(clazz)) {
            return 0L;
        } else if (float.class.equals(clazz) || Float.class.equals(clazz)) {
            return 0.0f;
        } else if (double.class.equals(clazz) || Double.class.equals(clazz)) {
            return 0.0d;
        } else if (String.class.equals(clazz)) {
            return "";
        } else if (Void.TYPE.equals(clazz)) {
            return "";
        }
        final Constructor[] constructors = clazz.getDeclaredConstructors();
        Constructor constructor = constructors[constructors.length - 1];
        constructor.setAccessible(true);
        final Class[] paramClasses = constructor.getParameterTypes();
        Object[] args = new Object[paramClasses.length];
        for (int i = 0; i < paramClasses.length; i++) {
            Class clazzes = paramClasses[i];
            if (clazzes.isPrimitive()) {
                args[i] = 0;
            } else {
                args[i] = null;
            }
        }
        return constructor.newInstance(args);
    }
}
